<template>
  <div class="material-list">
    <!-- 搜索卡片 -->
    <a-card :bordered="false" class="search-card">
      <a-form layout="inline" :model="searchForm">
        <a-form-item label="物料名称">
          <a-input
            v-model:value="searchForm.name"
            placeholder="请输入物料名称"
            allowClear
          />
        </a-form-item>
        <a-form-item label="规格型号">
          <a-input
            v-model:value="searchForm.model"
            placeholder="请输入规格型号"
            allowClear
          />
        </a-form-item>
        <a-form-item label="单位">
          <a-input
            v-model:value="searchForm.unit"
            placeholder="请输入单位"
            allowClear
          />
        </a-form-item>
        <a-form-item label="库存预警">
          <a-select
            v-model:value="searchForm.isLowStock"
            placeholder="请选择"
            style="width: 120px"
            allowClear
          >
            <a-select-option :value="true">是</a-select-option>
            <a-select-option :value="false">否</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button
              type="primary"
              :icon="h(SearchOutlined)"
              @click="fetchData"
            >
              搜索
            </a-button>
            <a-button :icon="h(ReloadOutlined)" @click="resetSearch">
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 数据表格 -->
    <a-card :bordered="false">
      <template #title>
        <span>物料列表</span>
        <a-tag color="blue" style="margin-left: 8px;">
          共 {{ dataSource.length }} 条
        </a-tag>
      </template>

      <template #extra>
        <a-button
          type="primary"
          :icon="h(PlusOutlined)"
          @click="showCreateModal"
        >
          新增物料
        </a-button>
      </template>

      <a-table
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        :pagination="pagination"
        :locale="{ emptyText: '暂无数据' }"
        @change="handleTableChange"
        :scroll="{ x: 1200, y: 800 }"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'stockStatus'">
            <a-tag :color="getStockStatusColor(record)">
              {{ getStockStatusText(record) }}
            </a-tag>
          </template>

          <template v-if="column.key === 'createdAt'">
            {{ formatDate(record.createdAt) }}
          </template>

          <template v-if="column.key === 'action'">
            <a-space>
              <a-button
                type="link"
                size="small"
                @click="showEditModal(record)"
              >
                编辑
              </a-button>
              <a-button
                type="link"
                size="small"
                danger
                @click="handleDelete(record)"
              >
                删除
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑物料弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      :title="isEdit ? '编辑物料' : '新增物料'"
      @ok="handleSubmit"
      :confirm-loading="submitLoading"
    >
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        layout="vertical"
      >
        <a-form-item label="物料名称" name="name" required>
          <a-input
            v-model:value="form.name"
            placeholder="请输入物料名称"
          />
        </a-form-item>

        <a-form-item label="规格型号" name="model">
          <a-input
            v-model:value="form.model"
            placeholder="请输入规格型号"
          />
        </a-form-item>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="当前库存" name="stockCount" required>
              <a-input-number
                v-model:value="form.stockCount"
                placeholder="请输入库存数量"
                :min="0"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="预警阈值" name="warningThreshold" required>
              <a-input-number
                v-model:value="form.warningThreshold"
                placeholder="请输入预警阈值"
                :min="0"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="单位" name="unit" required>
          <a-input
            v-model:value="form.unit"
            placeholder="请输入单位（如：个、件、箱）"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, h } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { useUserStore } from '@/stores/user'
import { useAppStore } from '@/stores/app'
import { getMaterialList, createMaterial, updateMaterial, deleteMaterial } from '@/api/material'
import type { Material, MaterialAddRequest, MaterialUpdateRequest, MaterialQueryRequest, PageResponse, PaginationState } from '@/types'
import { createPaginationFromResponse, handlePaginationNavigation } from '@/utils/pagination'
import type { FormInstance } from 'ant-design-vue'
import type { Rule } from 'ant-design-vue/es/form'
import {
  SearchOutlined,
  ReloadOutlined,
  PlusOutlined
} from '@ant-design/icons-vue'

const userStore = useUserStore()
const appStore = useAppStore()

const loading = ref(false)
const dataSource = ref<Material[]>([])

// 弹窗相关
const modalVisible = ref(false)
const submitLoading = ref(false)
const isEdit = ref(false)
const editId = ref<number>()

// 表单
const formRef = ref<FormInstance>()
const form = reactive<MaterialAddRequest>({
  name: '',
  model: '',
  stockCount: 0,
  warningThreshold: 0,
  unit: ''
})

// 搜索表单
const searchForm = reactive<MaterialQueryRequest>({
  name: '',
  model: '',
  unit: '',
  isLowStock: undefined,
  pageSize: 10,
  current: 1,
  lastId: 0
})

// 分页状态管理
const paginationState = ref<PaginationState>({
  current: 1,
  pageSize: 10,
  total: 0,
  pages: 0,
  hasNext: false,
  nextCursor: 0,
  previousPageCursors: []
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number, range: [number, number]) =>
    `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
})

// 当前页面的起始lastId
const currentPageLastId = ref(0)

// 表格列配置
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80
  },
  {
    title: '物料名称',
    dataIndex: 'name',
    key: 'name',
    width: 120
  },
  {
    title: '规格型号',
    dataIndex: 'model',
    key: 'model',
    width: 120
  },
  {
    title: '当前库存',
    dataIndex: 'stockCount',
    key: 'stockCount',
    width: 100,
    customRender: ({ text, record }: { text: number, record: Material }) => {
      return `${text} ${record.unit}`
    }
  },
  {
    title: '预警阈值',
    dataIndex: 'warningThreshold',
    key: 'warningThreshold',
    width: 100
  },
  {
    title: '库存状态',
    key: 'stockStatus',
    width: 100
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
    width: 120
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right' as const
  }
]

// 表单验证规则
const rules: Record<string, Rule[]> = {
  name: [
    { required: true, message: '请输入物料名称', trigger: 'blur' },
    { min: 2, max: 50, message: '物料名称长度为2-50个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '描述不能超过200个字符', trigger: 'blur' }
  ],
  stockCount: [
    { required: true, message: '请输入库存数量', trigger: 'blur' }
  ],
  warningThreshold: [
    { required: true, message: '请输入预警阈值', trigger: 'blur' }
  ],
  unit: [
    { required: true, message: '请输入单位', trigger: 'blur' },
    { max: 10, message: '单位长度不能超过10个字符', trigger: 'blur' }
  ]
}

// 格式化日期
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString()
}

// 获取库存状态颜色
const getStockStatusColor = (record: Material) => {
  if (record.stockCount <= record.warningThreshold) {
    return 'orange'
  }
  return 'green'
}

// 获取库存状态文本
const getStockStatusText = (record: Material) => {
  if (record.stockCount <= record.warningThreshold) {
    return '库存预警'
  }
  return '库存正常'
}

// 获取物料列表
const fetchData = async (resetPagination = false, useLastId?: number) => {
  try {
    loading.value = true

    if (resetPagination) {
      // 重置分页状态
      paginationState.value = {
        current: 1,
        pageSize: searchForm.pageSize || 10,
        total: 0,
        pages: 0,
        hasNext: false,
        nextCursor: 0,
        previousPageCursors: []
      }
      currentPageLastId.value = 0
    }

    const queryParams = { ...searchForm }
    queryParams.pageSize = paginationState.value.pageSize
    queryParams.current = paginationState.value.current
    queryParams.lastId = useLastId !== undefined ? useLastId : currentPageLastId.value

    const response = await getMaterialList(queryParams)
    if (response.code === 0 && response.data) {
      const pageData = response.data as PageResponse<Material>

      // 更新数据源
      dataSource.value = pageData.records || []

      // 更新分页状态
      paginationState.value = {
        current: pageData.current,
        pageSize: pageData.size,
        total: pageData.total,
        pages: pageData.pages,
        hasNext: pageData.hasNext,
        nextCursor: pageData.nextCursor,
        previousPageCursors: paginationState.value.previousPageCursors
      }

      // 更新分页配置
      const paginationConfig = createPaginationFromResponse(pageData)
      Object.assign(pagination, paginationConfig)
    }
  } catch (error) {
    console.error('获取物料列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.model = ''
  searchForm.unit = ''
  searchForm.isLowStock = undefined
  fetchData(true)
}

// 表格变化处理
const handleTableChange = (pag: any) => {
  const isNextPage = pag.current > paginationState.value.current
  const isPrevPage = pag.current < paginationState.value.current

  // 更新页面大小
  if (pag.pageSize !== paginationState.value.pageSize) {
    searchForm.pageSize = pag.pageSize
    paginationState.value.pageSize = pag.pageSize
    fetchData(true) // 页面大小变化时重置分页
    return
  }

  if (isNextPage && paginationState.value.hasNext) {
    // 向前翻页
    const navResult = handlePaginationNavigation(
      paginationState.value,
      'next',
      currentPageLastId.value
    )

    paginationState.value.current = navResult.current
    paginationState.value.previousPageCursors = navResult.previousCursors
    currentPageLastId.value = navResult.lastId

    fetchData(false, navResult.lastId)
  } else if (isPrevPage && paginationState.value.current > 1) {
    // 向后翻页
    const navResult = handlePaginationNavigation(
      paginationState.value,
      'prev',
      currentPageLastId.value
    )

    paginationState.value.current = navResult.current
    paginationState.value.previousPageCursors = navResult.previousCursors
    currentPageLastId.value = navResult.lastId

    fetchData(false, navResult.lastId)
  }
}

// 显示新增弹窗
const showCreateModal = () => {
  isEdit.value = false
  editId.value = undefined
  formRef.value?.resetFields()
  form.name = ''
  form.model = ''
  form.stockCount = 0
  form.warningThreshold = 0
  form.unit = ''
  modalVisible.value = true
}

// 显示编辑弹窗
const showEditModal = (record: Material) => {
  isEdit.value = true
  editId.value = record.id
  form.name = record.name
  form.model = record.model
  form.stockCount = record.stockCount
  form.warningThreshold = record.warningThreshold
  form.unit = record.unit
  modalVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    submitLoading.value = true

    if (isEdit.value) {
      // 编辑
      const updateData: MaterialUpdateRequest = {
        id: editId.value!,
        name: form.name,
        model: form.model,
        unit: form.unit,
        stockCount: form.stockCount,
        warningThreshold: form.warningThreshold
      }
      const response = await updateMaterial(updateData)
      if (response.code === 0) {
        message.success(response.message || '物料更新成功')
        modalVisible.value = false
        fetchData()
      } else {
        message.error(response.message || '更新失败')
      }
    } else {
      // 新增
      const response = await createMaterial(form)
      if (response.code === 0) {
        message.success(response.message || '物料创建成功')
        modalVisible.value = false
        fetchData()
      } else {
        message.error(response.message || '创建失败')
      }
    }
  } catch (error: any) {
    console.error('操作失败:', error)
    if (error?.response?.data?.message) {
      message.error(error.response.data.message)
    } else if (error?.message) {
      message.error(error.message)
    } else {
      message.error('操作失败，请重试')
    }
  } finally {
    submitLoading.value = false
  }
}

// 删除物料
const handleDelete = (record: Material) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除物料 "${record.name}" 吗？此操作不可恢复。`,
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      try {
        const response = await deleteMaterial({ id: record.id })
        if (response.code === 0) {
          message.success('删除成功')
          fetchData()
        }
      } catch (error) {
        console.error('删除物料失败:', error)
      }
    }
  })
}

onMounted(() => {
  // 检查权限
  if (!userStore.isRepairWorker && !userStore.isAdmin) {
    message.error('没有权限访问此页面')
    return
  }

  // 设置面包屑
  appStore.setBreadcrumbs([
    { title: '首页', path: '/dashboard' },
    { title: '物料管理' },
    { title: '物料列表' }
  ])

  fetchData()
})
</script>

<style scoped>
.material-list {
  padding: 0;
}

.search-card {
  margin-bottom: 16px;
  padding-bottom: 20px;
}

.search-card .ant-form {
  gap: 16px;
}

.search-card :deep(.ant-card-body) {
  padding-bottom: 0;
}
</style>
